/*
 * 
* Copyright (C) 2004-2010  Autodesk, Inc.
* 
* This library is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser
* General Public License as published by the Free Software Foundation.
* 
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
* 
 */


#include "stdafx.h"
#include "MapInfoCSOverrideFile.h"


using namespace std;

MapInfoCSOverrideFile::~MapInfoCSOverrideFile (void)
{
}

MapInfoCSOverrideFile::MapInfoCSOverrideFile (const wchar_t* name)
{
    mWKT = FdoStringP(L"");
    ErrorCode code;

    if (OpenFile (name, IDF_OPEN_READ, code))
    {
        unsigned long  size;
        
        if (FdoCommonFile::GetFileSize (size))
        {
            char* buffer = new char[size + 1];

            if ( !FdoCommonFile::ReadFile( buffer, size ) )
                throw FdoCommonFile::LastErrorToException (L"MapInfoCSOverrideFile::MapInfoCSOverrideFile", name);
            else
            {
                buffer[size] = '\0'; // EOF
                mWKT = FdoStringP( buffer );
            }

            delete[] buffer;
        }
        else
            throw FdoCommonFile::LastErrorToException (L"MapInfoCSOverrideFile::MapInfoCSOverrideFile", name);
    }
    else
        throw FdoCommonFile::ErrorCodeToException (code, name, IDF_OPEN_READ);
}

MapInfoCSOverrideFile::MapInfoCSOverrideFile (const wchar_t* name, const wchar_t* wkt) :
    mWKT( wkt )
{
    ErrorCode code;
    OpenFlags flags = (OpenFlags)(IDF_CREATE_NEW | IDF_OPEN_UPDATE);
    if (FileExists(name))
        flags = IDF_OPEN_UPDATE;

    if (OpenFile (name, flags, code))
    {
        // Convert to UTF8
        char* wkt2 = (char *)(const char *)mWKT; 

        if (!WriteFile (wkt2, (long) strlen(wkt2)))
            throw FdoCommonFile::LastErrorToException (L"MapInfoCSOverrideFile::MapInfoCSOverrideFile(wkt)", name);

        CloseFile ();
    }
    else
        throw FdoCommonFile::ErrorCodeToException (code, name, (OpenFlags)(IDF_CREATE_NEW | IDF_OPEN_UPDATE));
 }

FdoStringP MapInfoCSOverrideFile::GetWKT()
{
    return mWKT;
}

void MapInfoCSOverrideFile::SetWKT( FdoString* wkt )
{
    mWKT = FdoStringP( wkt );
}

